<?php
require_once 'conf.php';
require_once 'services/ResponseParser.php';
require_once 'services/CommunicationServices.php';
require_once 'viewbean/User.php';

class SecurityService {

	public function createUser($parameters){
		$username = $parameters["username"];
		$email = $parameters["email"];
		$name = $parameters["name"];
		$surname = $parameters["surname"];
		$generatedPass = $this->generatePassword();
		$hashedPass = md5($generatedPass);
		$id = $this->getMaxIdFromTable("user")+1;

		if ($this->isUserExist($username)){
			throw new Exception('022');
		}

		if ($this->isUserEmailExist($email)){
			throw new Exception('023');
		}

		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("insert into user (id, username, password, name, surname, email, created, active) values (:id, :username, :password, :name, :surname, :email, NOW(), 1)");
			$stmt->bindParam(':password', $hashedPass);
			$stmt->bindParam(':username', $username);
			$stmt->bindParam(':name', $name);
			$stmt->bindParam(':surname', $surname);
			$stmt->bindParam(':email', $email);
			$stmt->bindParam(':id', $id);

			$stmt->execute();

			$to = $email;
			$subject = "Your GRS Account Details";
			$body = "You or someone has created and account on GRS. Here are the details: \n\n username: ".$username. "\n password: ".$generatedPass. "\n";

			$communicator = new CommunicationServices;
			$communicator->sendEmail($to, $subject, $body);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('019');
		}

		$responder = new Responder;
		return $responder->constructResponse(null);
	}

	private function getMaxIdFromTable($table){
		$maxId = 0;
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select max(id) as id from ".$table);

			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$maxId = $row["id"];
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('004');
		}
		return $maxId;
	}

	public function resetPassword($parameters){
		$username = $parameters["username"];
		$generatedPass = $this-> generatePassword();
		$hashedPass = md5($generatedPass);

		try {
			if (!($this->isUserExist($username))){
				throw new Exception('020');
			}

			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("update user set password=:password where username=:username");
			$stmt->bindParam(':password', $hashedPass);
			$stmt->bindParam(':username', $username);

			$stmt->execute();

			$to = $this->getUserEmailAddress($username);
			$subject = "Password Reset";
			$body = "You or someone has requested a password reset on GRS. Here are the details: \n\n username: ".$username. "\n password: ".$generatedPass. "\n";

			$communicator = new CommunicationServices;
			$communicator->sendEmail($to, $subject, $body);

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('019');
		}

		$responder = new Responder;
		return $responder->constructResponse(null);
	}

	public function getUserEmailAddress($username){
		$emailaddres = "";
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select email from user where username= :username");
			$stmt->bindParam(':username', $username);

			$count = 0;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$emailaddres = $row["email"];
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('004');
		}
		return $emailaddres;
	}

	private function generatePassword(){
		$chars = "abcdefghijkmnopqrstuvwxyz023456789";

		srand((double)microtime()*1000000);
		$i = 0;
		$pass = '' ;
		while ($i <= 7) {
			$num = rand() % 33;
			$tmp = substr($chars, $num, 1);
			$pass = $pass . $tmp;
			$i++;
		}

		return $pass;
	}

	private function isUserExist($username){
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select * from user where username= :username");
			$stmt->bindParam(':username', $username);

			$count = 0;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$count++;
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		if ($count > 0){
			return true;
		} else {
			return false;
		}
	}

	private function isUserEmailExist($emailaddress){
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select * from user where email= :email");
			$stmt->bindParam(':email', $emailaddress);

			$count = 0;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$count++;
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		if ($count > 0){
			return true;
		} else {
			return false;
		}
	}

	public function updateUserDetails($parameters){
		$userid= $parameters["userid"];
		$name = $parameters["name"];
		$surname = $parameters["surname"];
		$username = $parameters["username"];
		$password = $parameters["password"];
		$hashedPass = md5($password);
		$email = $parameters["email"];

		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$stmt = $con->prepare("update user set username=:username, password=:password, name=:name, surname=:surname, email=:email where id=:userid");
			$stmt->bindParam(':userid', $userid);
			$stmt->bindParam(':name', $name);
			$stmt->bindParam(':surname', $surname);
			$stmt->bindParam(':username', $username);
			$stmt->bindParam(':password', $hashedPass);
			$stmt->bindParam(':email', $email);

			$stmt->execute();

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('019');
		}
	}


	public function getUserDetails($parameters){
		$userid = $parameters["userid"];
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$stmt = $con->prepare("select * from user where id= :userid");
			$stmt->bindParam(':userid', $userid);

			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$user = new User($row["id"], $row["username"], $row["password"], $row["name"], $row["surname"], $row["email"]);
				}
			}

		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			die();
			throw new Exception('018');
		}

		$responder = new Responder;
		return $responder->constructResponse($user);
	}

	public function loginUser($username, $password){
		$result = false;
		try {
			$con = new PDO(GlobalConfig::db_pdo_connect_string, GlobalConfig::db_username, GlobalConfig::db_password);
			$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$stmt = $con->prepare("select * from user where username= :username");
			$stmt->bindParam(':username', $username);

			$returnUsername = "";
			$returnPassword = "";
			$userid = "";
			$active = 0;
			if ($stmt->execute()){
				while ($row = $stmt->fetch()){
					$returnUsername = $row["username"];
					$returnPassword = $row["password"];
					$userid = $row["id"];
					$active = $row["active"];
				}
			}

			error_log("retUSer: ".$returnUsername.", user:". $username);
			if (($username == $returnUsername) && (md5($password) == $returnPassword )){

				if ($active == false){
					throw new Exception('024');
				}

				if (session_start()){
					$_SESSION["username"] = $username;
					$_SESSION["password"] = $password;
					$_SESSION["userid"] = $userid;
					$result = true;
				} else {
					throw new Exception('001');
				}

			} else {
				throw new Exception('002');
			}
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			throw new Exception('001');
		}
		return $result;
	}

	public function logoutUser($parameters){
		header( 'Location: /index.html' );
		$_SESSION['username'] = null;
		$_SESSION['password'] = null;
		$_SESSION['userid'] = null;
		session_start();
		session_destroy();

		$responder = new Responder;
		return $responder->constructResponse(null);
	}

}


?>